<template>
  <div class="repair-form">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-select v-model="formSearch.status" placeholder="请选择状态">
              <el-option label="待接单" value="待接单"></el-option>
              <el-option label="进行中" value="进行中"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div class="table">
      <el-table :data="empData" style="width: 100%">
        <el-table-column type="index" label="序号" width="60px" align="center">
        </el-table-column>
        <el-table-column prop="engineer_name" label="工程名称" width="300px" align="center">
        </el-table-column>
        <el-table-column prop="device_name" label="设备名称"  align="center">
        </el-table-column>
        <el-table-column prop="bill_why" label="问题描述" align="center">
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == '进行中'" type="success">{{ scope.row.status }}</el-tag>
            <el-tag v-else-if="scope.row.status == '已完成'" type="warning">{{ scope.row.status }}</el-tag>
            <el-tag v-else type="danger">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="工单类型" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-link type="primary" :underline="false" @click="toJump(scope.row)">详情</el-link>
            <el-link type="danger" :underline="false" style="margin-left:10px" @click="toDelete(scope.row.id)">取消</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.page"
        :page-sizes="[ 10, 20, 30]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { get,post,del } from '@/utils/request'
export default {
  data() {
    return {
      //搜索表单
      formSearch: {
        name: '',
        status: ''
      },
      //表格数据源
      empData: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 10
      },
    };
  },
  methods: {
    // 详情
    toJump(row) {
      // 路由跳转 
      this.$router.push({
        path: '/workorder/detail',
        query: row
      })
    },

    //去取消
    toDelete(id) {
      this.$confirm('是否确定取消?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async () => {
        //点击确认按钮 发送删除请求
        let res = await del('/workorder/deleteById', { id: id });
        //查询完从第一页载入数据
        this.params.page = 1;
        //重新载入数据
        this.getEmpData();
        this.$message({
          type: 'success',
          message: res.message
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getEmpData();
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.params.page = val;
      this.getEmpData();
    },
    //去查询
    toSearch() {
      this.params.page = 1; 
      this.getEmpData();
    },
    async getEmpData() {
      try {
        const temp = {
          ...this.params,
          ...this.formSearch
        };
        
        const res = await get('/workorder/pageQuery', temp, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        this.empData = res.data?.list || [];
        this.total = res.data?.total || 0;
      } catch (error) {
        console.error('获取工单列表失败:', error);
        if (error.response && error.response.status === 401) {
          this.$message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          this.$message.error('获取工单列表失败');
        }
      }
    },
    async handleRepairData() {
      const { device, reason } = this.$route.query;
      if (device && reason) {
        try {
          const deviceParts = device.split(',');
          await post('/workorder/saveOrUpdate', {
            engineer_name: deviceParts[0] || '未知工程',
            device_name: deviceParts[1] || '未知设备',
            bill_why: reason,
            status: '待接单',
            type: '维修工单'
          }, {
            headers: {
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
          });
          
          this.$message.success('工单创建成功');
          this.params.page = 1;
          await this.getEmpData();
        } catch (error) {
          console.error('工单创建失败:', error);
          if (error.response && error.response.status === 401) {
            this.$message.error('登录已过期，请重新登录');
            this.$router.push('/login');
          } else {
            this.$message.error('工单创建失败');
          }
        }
      }
    }
  },
  watch: {
    '$route.query': {
      immediate: true,
      handler(newVal) {
        if (newVal.device && newVal.reason) {
          this.handleRepairData();
        }
      }
    }
  },
  created() {
    this.handleRepairData();
    this.getEmpData();
  },
};
</script>
<style lang="scss" scoped>
.repair-form {
  padding: 10px;
}
.el-link {
  font-size: 12px;
}
</style>